package com.sensePlusVR.manager;

import android.annotation.SuppressLint;

import com.alibaba.fastjson.JSON;
import com.sensePlusVR.application.VRApplication;
import com.sensePlusVR.bean.CommendItem;
import com.sensePlusVR.bean.ServerErrorMsg;
import com.sensePlusVR.bean.ZambiaItem;
import com.sensePlusVR.net.NetCallBack;
import com.sensePlusVR.net.NetRequestManager;
import com.sensePlusVR.net.RequestUtils;
import com.sensePlusVR.utils.Constant;
import com.sensePlusVR.utils.ConstantURL;
import com.sensePlusVR.utils.MyLog;
import com.sensePlusVR.utils.MySharedPreferences;

import org.apache.http.Header;
import org.apache.http.entity.ByteArrayEntity;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("deprecation")
@SuppressLint("UseSparseArrays")
public class CommendItemManager extends BaseManager{
	private static final String TAG = CommendItemManager.class.getSimpleName();
	public static final int EventCommendGot = 0;
	public static final int EventCommendChanaged = 1;
	
	public static final int EventErrorBase = 100;
	
	private static CommendItemManager INSTANTS;
	

	private static Object tasklock;
	private static Map<Integer, DownloadTask> tasks;
	
	static public CommendItemManager getInstants(){
		
		if (INSTANTS == null){
			INSTANTS = new CommendItemManager();
			tasklock = new Object();
			tasks = new HashMap<Integer, DownloadTask>();
		}
		return INSTANTS;
	}
	
	public CommendItem getCommend(int gameId){
		CommendItem item = CommendItem.getCommendItembyId(gameId);
		if (item == null){
			synchronized(tasklock){
				if (!tasks.containsKey(gameId)) {
					DownloadTask task = new DownloadTask(gameId);
					task.start();
					tasks.put(gameId, task);
				}
			}

		}
		
		return item;
	}
	
	private void delTask(int gameId){
		synchronized(tasklock){
			if (tasks.containsKey(gameId)) {
				tasks.remove(gameId);
			}
		}
	}
	
	private class callbackThread extends Thread{
		private int event;
		private CommendItem item;
		public callbackThread(int event, CommendItem item){
			this.event = event;
			this.item = item;
		}
		@Override
		public void run() {
			callEventListener(event, item);
		}
	}
	
	private void callbackInThread(int event, CommendItem item){
		callbackThread th = new callbackThread(event, item);
		th.start();
	}
	
	public void setCommend(int gameId){
		
		CommendItem item = CommendItem.getCommendItembyId(gameId);
		if (item != null) {
			int up = 1 + item.getUp();
			item.setUp(up);
			item.setUserAction(1);
			CommendItem.saveOrUpdate(item);
			callbackInThread(EventCommendChanaged, item);
		}
		UploadTask task = new UploadTask(gameId);
		task.start();
	}
	
	public class DownloadTask{
		private int gameId;
		//private int userId;
		
		public DownloadTask(int gameId){
			this.gameId = gameId;
			//this.userId = userId;
		}
		
		public void start(){
			MyLog.d(TAG, "gameId : " + gameId );
			
			String url = ConstantURL.GET_GAME_RATINGS + "&resid=" + gameId ;
			MyLog.d(TAG, "getGameRatings url : " + url);
			
			String token = MySharedPreferences.getString2(VRApplication.getAppContext(),MySharedPreferences.NAME_NOT_CLEAR, Constant.LOGIN_SUCCESS_TOKEN);
			MyLog.d(TAG, "token getGameRatings : " + token);
			RequestUtils.clientToken.addHeader(Constant.STR_X_AUTH_TOKEN,token);

			RequestUtils.clientTokenGet(VRApplication.getAppContext(), url,  new NetCallBack(){
				@Override
				public void onMyStart() {
					super.onMyStart();
					MyLog.d(TAG, "onMyStart...");
				}
				
				@Override
				public void onMySuccess(int statusCode, Header[] aheader,
						JSONObject jsonobject) {
					super.onMySuccess(statusCode, aheader, jsonobject);
					if(jsonobject == null){
						MyLog.e(TAG, "getGameRatings onMySuccess jsonobject == null");
						return;
					}
					MyLog.d(TAG, "getGameRatings onMySuccess jsonobject : " + jsonobject.toString());
					
					if (statusCode == 200) {
						CommendItem commendItem = JSON.parseObject(jsonobject.toString(), CommendItem.class);
						MyLog.d(TAG, "commendItem : " + commendItem.toString());
						commendItem.setId(gameId);
						CommendItem.saveOrUpdate(commendItem);
						callEventListener(EventCommendGot, commendItem);
						delTask(gameId);
					}
					
				}
				
				@Override
				public void onMyFailure(int statusCode, Header[] headers,
						Throwable throwable, JSONObject errorResponse) {
					super.onMyFailure(statusCode, headers, throwable, errorResponse);
					NetRequestManager.isCommonErr(statusCode, errorResponse, VRApplication.getAppContext());
				}
			});

		}

	}
	
	
	public class UploadTask{
		private int gameId;
		
		public UploadTask(int gameId){
			this.gameId = gameId;
		}
		
		public void start(){
			MyLog.d(TAG, "uploadZambiaOrStamp gameId : " + gameId);
			
			ZambiaItem zambiaItem = new ZambiaItem();
			zambiaItem.setResid(gameId);
			zambiaItem.setAction("up");
			String json = JSON.toJSONString(zambiaItem);
			
			String token = MySharedPreferences.getString2(VRApplication.getAppContext(), MySharedPreferences.NAME_NOT_CLEAR,Constant.LOGIN_SUCCESS_TOKEN);
			MyLog.d(TAG, "token uploadZambiaOrStamp : " + token);
			RequestUtils.clientToken.addHeader(Constant.STR_X_AUTH_TOKEN,token);
			 
			RequestUtils.clientTokenPost(VRApplication.getAppContext(),ConstantURL.GAME_RATING, new ByteArrayEntity(json.getBytes()),Constant.STR_APPLICATION_JSON, new NetCallBack(){
				
				@Override
				public void onMySuccess(int statusCode, Header[] aheader,
						JSONObject jsonobject) {
					super.onMySuccess(statusCode, aheader, jsonobject);
					MyLog.d(TAG, "uploadZambiaOrStamp onMySuccess statusCode : "
							+ statusCode);
					if(jsonobject == null){
						MyLog.d(TAG, "uploadZambiaOrStamp jsonobject == null");
						return;
					}
					MyLog.d(TAG, "uploadZambiaOrStamp onMySuccess jsonobject : "
							+ jsonobject.toString());
					
					if (statusCode == 200) {
						ServerErrorMsg msg = JSON.parseObject(jsonobject.toString(), ServerErrorMsg.class);
						if(msg.getError().equals(Constant.SERVER_SUCCESS_KEY_E000)){
							MyLog.d(TAG, "uploadZambiaOrStamp success");
							//getGameRatings(item,position,true);
							
							return;
						}
					}
					MyLog.e(TAG, "uploadZambiaOrStamp failed");
				}
				@Override
				public void onMyFailure(int statusCode, Header[] headers,
						Throwable throwable, JSONObject errorResponse) {
					super.onMyFailure(statusCode, headers, throwable, errorResponse);
					callEventListener(EventErrorBase + EventCommendChanaged, Integer.valueOf(gameId));
					NetRequestManager.isCommonErr(statusCode, errorResponse, VRApplication.getAppContext());
				}
			});
		}
	}
	
}
